# xiaonei 的辅助方法集合
# 部分代码来自于 facebooker 的 Helpers module
module Helpers

  XN_NAME_OPTION_KEYS_TO_TRANSFORM = {
    :show_network => :shownetwork
  } 
  XN_NAME_VALID_OPTION_KEYS = [:linked, :shownetwork] 
  
  VALID_XN_PROFILE_PIC_SIZES = [:tiny, :normal, :main]

  def xn_name(user, options={})
    options = options.dup
    options.transform_keys!(XN_NAME_OPTION_KEYS_TO_TRANSFORM)
    options.assert_valid_keys(XN_NAME_VALID_OPTION_KEYS)
    options.merge!(:uid => cast_to_xiaonei_id(user))
    tag("xn:name", stringify_vals(options))
  end 

  def xn_profile_pic(user, options={})
    options = options.dup
    validate_xn_profile_pic_size(options)
    options.merge!(:uid => cast_to_xiaonei_id(user))
    tag("xn:profile-pic", stringify_vals(options))
  end 

  def xn_profile_pic_with_id(user_id, options={})
    options = options.dup
    validate_xn_profile_pic_size(options)
    options.merge!(:uid => user_id)
    tag("xn:profile-pic", stringify_vals(options))
  end   

  def xn_name_with_id(user_id, options={})
    options = options.dup
    options.transform_keys!(XN_NAME_OPTION_KEYS_TO_TRANSFORM)
    options.assert_valid_keys(XN_NAME_VALID_OPTION_KEYS)
    options.merge!(:uid => user_id)
    tag("xn:name", stringify_vals(options))
  end     

  protected

  def cast_to_xiaonei_id(object)
    # User
    if object.respond_to?(:uid)
      object.uid
      # Friend
    elsif object.respond_to?(:id)
      object.id
    end
  end 

  def validate_xn_profile_pic_size(options)
    if options.has_key?(:size) && !VALID_XN_PROFILE_PIC_SIZES.include?(options[:size].to_sym)
      raise(ArgumentError, "Unkown value for size: #{options[:size]}")
    end
  end 
  

  private
  def stringify_vals(hash)
    result={}
    hash.each do |key,value|
      result[key]=value.to_s
    end
    result
  end 
end

class Hash
  def transform_keys!(transformation_hash)
    transformation_hash.each_pair{|key, value| transform_key!(key, value)}
  end

  
  def transform_key!(old_key, new_key)
    swapkey!(new_key, old_key)
  end

  ### This method is lifted from Ruby Facets core
  def swapkey!( newkey, oldkey )
    self[newkey] = self.delete(oldkey) if self.has_key?(oldkey)
    self
  end
end

